package com.hankol.material.api

import android.app.Activity
import android.content.Context
import android.os.Bundle
import cc.shinichi.library.bean.ImageInfo
import com.baselibrary.Constants
import com.baselibrary.bean.download.DownloadInfo
import com.baselibrary.db.DBManager
import com.baselibrary.manager.SensorsDataManager
import com.baselibrary.router.ActivityRouter
import com.baselibrary.utils.*
import com.hankol.material.bean.MaterialContentInfo
import com.hankol.material.help.PopUtils
import com.hankol.material.limit.DownloadLimitManager
import com.hankol.material.view.ImagePreview
import com.hankol.material.viewmodel.MaterialBaseViewModel

/**
 * @author 关忆北丶
 * @description:
 * @date :2021/6/23 14:08
 */
public class MaterialConstants {
    companion object {
        const val BUSINESS_TYPE_SCREEN = 0x101//筛选界面
        const val BUSINESS_TYPE_SEARCH = 0x102//搜索界面
        const val BUSINESS_TYPE_FOLDER = 0x103//文件夹界面
        const val VIDEO_PLAY_SECONDS = "VIDEO_PLAY_SECONDS"
        const val VIDEO_PLAY_VOICE = "VIDEO_PLAY_VOICE"
        const val FOLDER_CONTENT = "folderContent"//更改文件名称
        const val DEF_FOLDER_NAME = "默认收藏夹"
        const val FOLDER_DETAIL = "folder_detail"//文件夹详情
        const val FOLDER_SCREEN = "folder_screen"//筛选~
        const val MATERIAL_IMG = "图片"
        const val MATERIAL_VIDEO = "视频"
        const val MATERIAL_FILE = "文档"


        /**素材库--打开图片详情
         * @author: merbng
         * @time: 2021/11/17 19:00
         * @description:
         */
        fun openImgDetail(context: Context, beanList: List<MaterialContentInfo.FileLibsBean.DataBean>, pos: Int, isFromCollect: Boolean = false) {
            val imageInfoList = mutableListOf<ImageInfo>()
            for (bean in beanList) {
                val imageInfo = ImageInfo()
                imageInfo.thumbnailUrl = bean.thumbnail
                imageInfo.originUrl = bean.fileUrl
                imageInfoList.add(imageInfo)
            }
            beanList[pos].isFromCollect = isFromCollect
            ImagePreview
                    .getInstance()
                    // 上下文，必须是activity，不需要担心内存泄漏，本框架已经处理好；
                    .setContext(context)
                    // 设置从第几张开始看（索引从0开始）
                    .setIndex(pos)
                    //=================================================================================================
                    // 有三种设置数据集合的方式，根据自己的需求进行三选一：
                    // 1：第一步生成的imageInfo List
                    .setImageInfoList(imageInfoList).setEnableClickClose(false)
                    .setBeanList(beanList)
                    // 2：直接传url List
                    //.setImageList(List<String> imageList)
                    // 3：只有一张图片的情况，可以直接传入这张图片的url
                    //.setImage(String image)
                    //=================================================================================================
                    // 开启预览
                    .start()
        }

        /**下载文件
         * @author: merbng
         * @time: 2021/11/4 14:14
         * @description:
         */

        @JvmStatic
        fun downloadFile(act: Activity, url: String, name: String = "", icon: String = "", total: Double, type: Int = -1) {
            //素材类型 全部:-1 图片:0 视频:1 文档:2
            SensorsDataManager.instance.materialLibraryDownload(name, if (type == 0) "图片" else if (type == 1) "视频" else "文档")
            //判断 是否文档 是否允许下载
            if (type == 2 && !SpUtils.getInstance().materialDocumentDownPermision) {
                ToastUtils.showShort(act, "暂不支持下载")
                return
            }
            if (!NetworkUtil.isWifiConnected(act)) {
                //流量
                PopUtils.showRightLeftDialog(act, "当前非WIFI网络\n是否使用流量下载", object : MaterialBaseViewModel.IRightLeftCallBack {
                    override fun leftClick() {

                    }

                    override fun rightClick() {
                        if (!NetworkUtil.isPhoneHasInternet(act)) {//无网络
                            NetworkUtil.openWirelessSettings(act)
                        } else {
                            downloadOption(url, name, icon, type, total, act)
                        }
                    }
                }, "取消", "使用流量下载")
                return
            }
            downloadOption(url, name, icon, type, total, act)
        }

        private fun downloadOption(url: String, name: String, icon: String, type: Int, total: Double, act: Activity) {
            if (!DownloadLimitManager.getInstance().getDownloadUrl(url)) {
                val userId = 36330
                val info = DownloadInfo(url)
                info.fileName = name
                info.fileIcon = icon
                info.userId = userId.toString() + ""
                info.time = TimeUtil.setYearMonthDay(TimeUtil.getCurrentTimeMillis())
                info.type = type
                info.total = 0 /*total.toLong()*/
                //判断当前正在下载的个数
                val downloadList = DBManager.getInstance()
                    .getDownloadList(SpUtils.getInstance().userId, false)
                val list = mutableListOf<DownloadInfo>()
                //已下载过的
                val alawaysdownloadList = mutableListOf<DownloadInfo>()
                for (datainfo in downloadList) {
                    if (datainfo.url.equals(url) && FileUtils.fileIsExists(datainfo.path)) {
                        //已下载过
                        alawaysdownloadList.add(datainfo)
                    }
                    if (datainfo.downloadStatus.equals(DownloadInfo.DOWNLOAD) || datainfo.downloadStatus.equals(DownloadInfo.DOWNLOAD_PAUSE) || datainfo.downloadStatus.equals(DownloadInfo.DOWNLOAD_WAIT))
                        list.add(datainfo)
                }
                info.downloadStatus = if (list.size >= DownloadLimitManager.maxCount) DownloadInfo.DOWNLOAD_WAIT else DownloadInfo.DOWNLOAD

                if (alawaysdownloadList.size > 0) {
                    ToastUtils.showShort(act,"大于0");
                    //已下载
                    PopUtils.showJoinDownloadDialog(act, alawaysdownloadList.get(0).downloadStatus.equals(DownloadInfo.DOWNLOAD_OVER))
                } else {
                    ToastUtils.showShort(act,"等于0");
                    DBManager.getInstance()
                        .saveDownload(SpUtils.getInstance().userId, info)
                    DownloadLimitManager.getInstance().download(info)
                    PopUtils.showJoinDownloadDialog(act)
                }
            } else {
                ToastUtils.showShort(act,"正在下载中");
                PopUtils.showJoinDownloadDialog(act, true)
            }
        }

        /**打开文档详情
         * @author: merbng
         * @time: 2021/11/17 21:13
         * @description:
         */
        fun openDocumentDetail(item: MaterialContentInfo.FileLibsBean.DataBean) {
            val bundle = Bundle()
            bundle.putSerializable(Constants.KEY_DOCUMENT_BEAN, item)
            ActivityRouter.startActivity(ActivityRouter.MATERIAL.DOCUMENT_DETAIL, bundle)
        }
    }
}